package util;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;

public class HttpUtil {
    public static String readBody(HttpServletRequest req) throws UnsupportedEncodingException {
        //1.先根据请求头里面的ContentLength获取到body的长度，单位是字节
        int contentLength = req.getContentLength();
        //2.按照这个长度准备好byte[]数组
        byte[] buf = new byte[contentLength];
        //3.获取到body的流对象
        try (InputStream inputStream = req.getInputStream()) {
            //4.基于这个流对象，读取内容，放入buf数组
            inputStream.read(buf);
        } catch (IOException e) {
            e.printStackTrace();
        }
        //5.将读取的buf转换成String对象
        return new String(buf, "utf-8");
    }
}
